<template>
	<div class="swiper" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend">
		<div class="swiper-box" :style="{width: swiperData.length * 100 + '%', left: left, transition: transition}">
			<div v-for="item in swiperData" :key="item.id">
				<img :src="item.picUrl" alt="">
			</div>
		</div>
	</div>
</template>

<script>
export default {
	name: 'swiper',
	props: ['swiperData'],
	data() {
		return {
			bannerList: [],
			left: '-100%',
			startX: '', // 定义触摸的初始值
			dir: 'left', // 定义触摸方向
			transition: 'none', // 过度定义
			timer1: '',
			timer2: '',
			timer3: '',
			move: ''
		};
	},
	watch: {},
	computed: {},
	created() {

	},
	mounted() {
		this.timer3 = setInterval(() => {
			this.dir = 'left';
			this.touchend();
		}, 3000);
	},
	methods: {
		touchstart(e) {
			this.startX = e.targetTouches[0].pageX;
		},
		touchmove(e) {
			this.move = e.targetTouches[0].pageX;
			if (e.targetTouches[0].pageX - this.startX > 30) {
				this.dir = 'right';
			} else if (e.targetTouches[0].pageX - this.startX < -30) {
				this.dir = 'left';
			}
		},
		touchend() {
			this.transition = 'left 0.5s linear';
			if (this.dir === 'left') {
				this.left = '-200%';
				clearTimeout(this.timer1);
				this.timer1 = setTimeout(() => {
					this.dir = 'left';
					this.transition = 'none';
					this.left = '-100%'
					let item = this.swiperData.shift();
					this.swiperData.push(item);
				}, 500);
			} else {
				this.left = 0;
				clearTimeout(this.timer2);
				this.timer2 = setTimeout(() => {
					this.dir = 'right';
					this.transition = 'none';
					this.left = '-100%'
					let item = this.swiperData.pop();
					this.swiperData.unshift(item);
				}, 500);
			}
		}
	},
	beforeDestroy() {
		clearInterval(this.timer3);
	}
};
</script>

<style lang="scss" scoped>
.swiper {
  overflow: hidden;
  position: relative;
  height: 100vw;

  .swiper-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: absolute;
    top: 0;

    img {
      width: 100%;
    }
  }
}
</style>